package com.party.jackclientandroid;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.party.jackclientandroid.controller.FragmentUserVisibleController;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.okhttp.RxSchedulers;
import com.party.jackclientandroid.photoselector.utils.StatusBarUtils;
import com.party.jackclientandroid.utils.ToastUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Tangxb on 2016/12/13.
 */

public abstract class BaseFragment extends Fragment implements FragmentUserVisibleController.UserVisibleCallback {
    protected BaseActivity mActivity;
    protected View mView;
    protected Fragment mFragment;
    protected MApplication mApplication;


    protected Resources mResources;
    private FragmentUserVisibleController userVisibleController;
    private Unbinder unbinder;


    protected CompositeDisposable compositeDisposable;
    public LoadViewHelper helper;

    public BaseFragment() {
        userVisibleController = new FragmentUserVisibleController(this, this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (BaseActivity) getActivity();
        mResources = getResources();
        mApplication = (MApplication) mActivity.getApplication();
        Bundle arg = getArguments();
        if (arg != null) {
            receiveBundleFromActivity(arg);
        }
        mFragment = this;
    }

    /**
     * 动态添加一个背景覆盖在状态栏上面
     */
//    private void dynamicAddStatusView() {
//        int statusBarHeight = StatusBarUtils.getStatusBarHeight(mActivity);
//        View statusView = new View(mActivity);
//        statusView.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.color_ffe252));
//        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
//        ll_container.addView(statusView, 0, layoutParams);
//    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(getLayoutResId(), container, false);
        bindButterKnife();
        init();
        return mView;
    }

    protected abstract int getLayoutResId();

    protected void bindButterKnife() {
        try {
            unbinder = ButterKnife.bind(this, mView);
        } catch (Exception e) {
        }
    }


    public void init() {
        initView();
        initData();
        initListener();

    }

    public boolean onFragmentBackPressed() {

        return false;
    }

    protected void initData() {

    }

    protected void initListener() {

    }

    protected void initView() {

    }

    protected void receiveBundleFromActivity(Bundle arg) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userVisibleController.activityCreated();
    }

    @Override
    public void onResume() {
        super.onResume();
        userVisibleController.resume();
        setKeyBack();
    }

    public void setKeyBack() {
        getView().setFocusable(true);
        getView().requestFocus();
        getView().setFocusableInTouchMode(true);
        getView().setOnKeyListener((View view, int i, KeyEvent keyEvent) -> {
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                return onFragmentBackPressed();
            }
            return false;
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        userVisibleController.pause();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        userVisibleController.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void setWaitingShowToUser(boolean waitingShowToUser) {
        userVisibleController.setWaitingShowToUser(waitingShowToUser);
    }

    @Override
    public boolean isWaitingShowToUser() {
        return userVisibleController.isWaitingShowToUser();
    }

    @Override
    public boolean isVisibleToUser() {
        return userVisibleController.isVisibleToUser();
    }

    @Override
    public void callSuperSetUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onVisibleToUserChanged(boolean isVisibleToUser, boolean invokeInResumeOrPause) {
        if (isVisibleToUser) {

        }
    }


    /**
     * 添加一个请求,子线程中执行然后切换回主线程
     *
     * @param observable
     */
    public <T> void addDisposableIoMain(Observable<T> observable, Consumer<T> consumer) {
        if (compositeDisposable == null) {
            synchronized (this) {
                if (compositeDisposable == null) {
                    compositeDisposable = new CompositeDisposable();
                }
            }
        }
        if (observable != null) {
            Observable<T> observableCompose = observable.compose(RxSchedulers.io_main());
            compositeDisposable.add(observableCompose.subscribe(consumer, (Throwable throwable) -> {
                System.out.println(consumer);
                showToast(consumer.getClass()+" = "+throwable.getMessage());
            }));
        }
    }

    /**
     * 添加一个请求,子线程中执行然后切换回主线程
     *
     * @param observable
     */
    public <T> void addDisposableIoMain(Observable<T> observable, Consumer<T> consumer, Consumer<Throwable> throwable) {
        if (compositeDisposable == null) {
            synchronized (this) {
                if (compositeDisposable == null) {
                    compositeDisposable = new CompositeDisposable();
                }
            }
        }
        if (observable != null) {
            Observable<T> observableCompose = observable.compose((ObservableTransformer<? super T, ? extends T>) RxSchedulers.io_main());
            compositeDisposable.add(observableCompose.subscribe(consumer, throwable));
        }
    }

    /**
     * 结束所有请求
     */
    public void removeCompositeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }

    public void showToast(String message) {
        ToastUtils.t(mApplication, message);
    }

    public void startActivity(Class clazz) {
        Intent intent = new Intent(mActivity, clazz);
        mActivity.startActivity(intent);
    }

    public void startMyActivity(Intent intent) {
        mActivity.startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeCompositeDisposable();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    public void onMyReStart() {

    }
}
